package com.dm.learn_rxjava_retrofit;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager.OnActivityResultListener;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.ref.WeakReference;

/**
 * @author damon.han
 * @Description: Main Activity
 */
public class BaseActivity extends AppCompatActivity implements IBaseActivity {

    public static final int VISIBLE = View.VISIBLE;
    public static final int GONE = View.GONE;

    public static final String TAG = "BaseActivity";
    private static WeakReference<BaseActivity> wrRunningActivity;
    private View rootView;
    private ProgressDialog progressBar;
    protected Context mContext = null;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
    }

    @Override
    public void setContentView(int layoutResID) {
        rootView = LayoutInflater.from(this).inflate(layoutResID, null);
        super.setContentView(rootView);
    }

    @Override
    protected void onResume() {
        super.onResume();
        wrRunningActivity = new WeakReference<BaseActivity>(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dismissProgressDialog();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (onBackClick())
                return super.onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }

    public boolean onBackClick() {
        finish();
        return true;
    }

    /**
     * 判断是否有网络连接,没有返回false
     */
    @Override
    public boolean hasInternetConnected() {
        ConnectivityManager manager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (manager != null) {
            NetworkInfo network = manager.getActiveNetworkInfo();
            if (network != null && network.isConnectedOrConnecting()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否有网络连接，若没有，则弹出网络设置对话框，返回false
     */
    @Override
    public boolean validateInternet() {
        ConnectivityManager manager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (manager == null) {
            openWirelessSet();
            return false;
        } else {
            NetworkInfo[] info = manager.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        openWirelessSet();
        return false;
    }

    /**
     * 判断GPS定位服务是否开启
     */
    @Override
    public boolean hasLocationGPS() {
        LocationManager manager = (LocationManager) mContext
                .getSystemService(Context.LOCATION_SERVICE);
        if (manager
                .isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断基站定位是否开启
     */
    @Override
    public boolean hasLocationNetWork() {
        LocationManager manager = (LocationManager) mContext
                .getSystemService(Context.LOCATION_SERVICE);
        if (manager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检查内存卡可读
     */
    @Override
    public void checkMemoryCard() {
        if (!Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())) {
            new AlertDialog.Builder(mContext)
                    .setTitle("检测内存卡")
                    .setMessage("请检查内存卡")
                    .setPositiveButton("设置",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    dialog.cancel();
                                    Intent intent = new Intent(
                                            Settings.ACTION_SETTINGS);
                                    mContext.startActivity(intent);
                                }
                            })
                    .setNegativeButton("退出",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    dialog.cancel();

                                }
                            }).create().show();
        }
    }

    /**
     * 打开网络设置对话框
     */
    public void openWirelessSet() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mContext);
        dialogBuilder
                .setTitle("网络设置")
                .setMessage("检查网络")
                .setPositiveButton("网络设置",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.cancel();
                                Intent intent = new Intent(
                                        Settings.ACTION_WIRELESS_SETTINGS);
                                mContext.startActivity(intent);
                            }
                        })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                });
        dialogBuilder.show();
    }


    /**
     * 返回上下文对象
     */
    @Override
    public Context getContext() {
        return mContext;
    }

    @Override
    public void firstInitData() {

    }

    @Override
    public void initViews() {

    }


    public void gotoActivity(Class<?> cls) {
        Intent intent;
        intent = new Intent(this, cls);
        startActivity(intent);
    }

    public void gotoActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(this, cls);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mActivityResultListener != null) {
            mActivityResultListener.onActivityResult(requestCode, resultCode,
                    data);
        }
    }

    private OnActivityResultListener mActivityResultListener;

    public void setOnActivityResultListener(OnActivityResultListener l) {
        this.mActivityResultListener = l;
    }

    @Override
    public void startService() {

    }

    @Override
    public void stopService() {

    }

    public void dismissProgressDialog() {
        if (progressBar != null && progressBar.isShowing()) {
            progressBar.cancel();
        }
    }

    public void showProgressDialog(String title, String msg) {
        showProgressDialog(title, msg, true);
    }

    public void showProgressDialog(String title, String msg,
                                   boolean cancelButton) {
        dismissProgressDialog();
        progressBar = new ProgressDialog(mContext);
        progressBar.setTitle(title);
        progressBar.setMessage(msg);
        progressBar.setCancelable(false);
        if (cancelButton) {
            progressBar.setButton(DialogInterface.BUTTON_NEGATIVE, "取消",
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            if (progressBar != null) {
                                progressBar.dismiss();
                            }
                        }

                    });
        }
        progressBar.show();
    }

    public void toast(int resId) {
        Toast.makeText(this, resId, Toast.LENGTH_SHORT).show();
    }


    public void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 从资源获取字符串
     *
     * @param resId
     * @return
     */
    public String getStr(int resId) {
        return getResources().getString(resId);
    }

    /**
     * 从EditText 获取字符串
     *
     * @param editText
     * @return
     */
    public String getStr(EditText editText) {
        return editText.getText().toString();
    }

    /**
     * 从EditText 获取字符串并trim
     *
     * @param editText
     * @return
     */
    public String getStrTrim(EditText editText) {
        return editText.getText().toString().trim();
    }


    /**
     * 从TextView 获取字符串
     *
     * @return
     */
    public String getStr(TextView textView) {
        return textView.getText().toString();
    }


    public void repaceFragment(int resId, Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(resId, fragment);
        transaction.commit();
    }
}
